package com.ilop.sthome.mvp.present.device;

import android.content.Context;
import android.content.Intent;

import com.example.common.base.OnCallBackToRefresh;
import com.example.common.mvp.BasePresenterImpl;
import com.ilop.sthome.common.CommonId;
import com.ilop.sthome.common.command.SendAutoCommand;
import com.ilop.sthome.data.enums.SmartDevice;
import com.ilop.sthome.data.greenDao.AutomationBean;
import com.ilop.sthome.data.greenDao.DeviceInfoBean;
import com.ilop.sthome.mvp.contract.device.SocketLinkageContract;
import com.ilop.sthome.ui.activity.scene.ChooseActionActivity;
import com.ilop.sthome.ui.activity.scene.SettingActionActivity;
import com.ilop.sthome.ui.activity.scene.SettingHumitureActivity;
import com.ilop.sthome.ui.activity.scene.SettingTempControlActivity;
import com.ilop.sthome.ui.dialog.BaseDialog;
import com.ilop.sthome.utils.CoderUtils;
import com.ilop.sthome.utils.greenDao.utils.AutomationDaoUtil;
import com.ilop.sthome.utils.greenDao.utils.DeviceDaoUtil;
import com.ilop.sthome.utils.tools.ByteUtil;
import com.siterwell.familywellplus.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author skygge
 * @date 2020-04-06.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class SocketLinkagePresenter extends BasePresenterImpl<SocketLinkageContract.IView> implements SocketLinkageContract.IPresent {

    private Context mContext;
    private String mRecommendId;
    private String mDeviceName;
    private int mMid;
    private int mPosition;
    private boolean isModify;
    private String mAutoCode;
    private AutomationBean mAutomation;
    private List<DeviceInfoBean> mInputList;
    private List<DeviceInfoBean> mOutputList;

    private SendAutoCommand mSendSceneData;

    public SocketLinkagePresenter(Context mContext, String recommendId) {
        this.mContext = mContext;
        this.mRecommendId = recommendId;
    }

    @Override
    public boolean getAutomationInfo(int mid, String deviceName) {
        this.mMid = mid;
        this.mDeviceName = deviceName;
        DeviceInfoBean mDeviceInfoBean = DeviceDaoUtil.getInstance().findGatewayByDeviceName(mDeviceName);
        mSendSceneData = new SendAutoCommand(mContext, mDeviceInfoBean);
        if (mid == -1){
            isModify = false;
            mAutomation = new AutomationBean();
        }else {
            isModify = true;
            mAutomation = AutomationDaoUtil.getInstance().findAutomationByMid(mid, deviceName);
        }
        return isModify;
    }

    @Override
    public void getInputList() {
        if (isModify){
            mInputList = mAutomation.getInputList();
        }else {
            mInputList = new ArrayList<>();
        }
        mView.showInputList(mInputList);
    }

    @Override
    public void getOutputList(String deviceName, int deviceId) {
        if (isModify){
            mOutputList = mAutomation.getOutputList();
        }else {
            DeviceInfoBean device = DeviceDaoUtil.getInstance().findByDeviceId(deviceName, deviceId);
            device.setDevice_status(getDefaultStatus(mRecommendId));
            mOutputList = new ArrayList<>();
            mOutputList.add(device);
        }
        mView.showOutputList(mOutputList);
    }

    @Override
    public void setInputList(List<DeviceInfoBean> deviceList) {
        mInputList = deviceList;
        mView.showInputList(deviceList);
    }

    @Override
    public void setOutputList(List<DeviceInfoBean> deviceList) {
        mOutputList = deviceList;
        mView.showOutputList(deviceList);
    }

    @Override
    public void addNewInput() {
        Intent addItem = new Intent(mContext, ChooseActionActivity.class);
        addItem.putExtra(CommonId.KEY_INPUT, true);
        addItem.putExtra(CommonId.KEY_LINKAGE, true);
        addItem.putExtra(CommonId.KEY_DEVICE_NAME, mDeviceName);
        mView.startActivityByIntent(addItem);
    }

    @Override
    public void updateAction(boolean isInput, int position) {
        this.mPosition = position;
        DeviceInfoBean device;
        if (isInput){
            device = mInputList.get(position);
        }else {
            device = mOutputList.get(position);
        }
        Intent intent = new Intent();
        intent.putExtra(CommonId.KEY_INPUT, isInput);
        intent.putExtra(CommonId.KEY_UPDATE, true);
        intent.putExtra(CommonId.KEY_DEVICE, device);

        if(SmartDevice.EE_DEV_TH_CHECK == SmartDevice.getType(device.getDevice_type())){
            intent.setClass(mContext, SettingHumitureActivity.class);
            mView.startActivityByIntent(intent);
        }else if(SmartDevice.EE_TEMP_CONTROL == SmartDevice.getType(device.getDevice_type())){
            intent.setClass(mContext, SettingTempControlActivity.class);
            mView.startActivityByIntent(intent);
        }else {
            intent.setClass(mContext, SettingActionActivity.class);
            mView.startActivityByIntent(intent);
        }
    }

    @Override
    public void deleteAction(boolean isInput) {
        if (isInput){
            mInputList.remove(mPosition);
            setInputList(mInputList);
        }else {
            mOutputList.remove(mPosition);
            setOutputList(mOutputList);
        }
    }

    @Override
    public void onSendAutomation() {
        if (mInputList.size() == 0){
            mView.showMsg(mContext.getString(R.string.intput_must_has_eq));
            return;
        }
        mView.showProgress();
        if(!isModify){
            String finalCode = CoderUtils.getNewCodeLinkage(mRecommendId, mInputList, mOutputList);
            String finalCRC = ByteUtil.stringToCRC(finalCode);
            mAutoCode = "FFFF" + finalCode + finalCRC;
            mSendSceneData.increaseAutomation(mAutoCode.toUpperCase());
        }else {
            String autoId = CoderUtils.setCodeSupplement2Byte(Integer.toHexString(mAutomation.getMid()));
            String finalCode = CoderUtils.getNewCodeLinkage(mRecommendId, mInputList, mOutputList);
            String finalCRC = ByteUtil.stringToCRC(finalCode);
            mAutoCode = autoId + finalCode + finalCRC;
            mSendSceneData.updateAutomation(mAutoCode.toUpperCase());
        }
    }

    @Override
    public void onSendSuccess(String autoId) {
        ExecutorService mExecutorService = Executors.newSingleThreadExecutor();
        String finalCode = isModify ? mAutoCode : autoId + mAutoCode.substring(4);
        Runnable runnable = () -> CoderUtils.analysisFullCode(finalCode.toUpperCase(), mDeviceName);
        mExecutorService.execute(runnable);
        mView.finishActivity();
    }

    @Override
    public void onDeleteAutomation() {
        mSendSceneData.deleteAutomation(mMid);
    }

    @Override
    public void onDeleteSuccess() {
        if(mMid>-1){
            AutomationDaoUtil.getInstance().deleteByMid(mMid, mDeviceName);
            mView.finishActivity();
        }
    }

    @Override
    public boolean checkInput(DeviceInfoBean device) {
        if (mInputList.size()>0) {
            for (DeviceInfoBean input : mInputList) {
                if (input.getDevice_type().equals(device.getDevice_type()) &&
                        input.getDevice_status().equals(device.getDevice_status())) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void checkUpdateInput(DeviceInfoBean device) {
        mInputList.set(mPosition, device);
        setInputList(mInputList);
    }

    @Override
    public void checkUpdateOutput(DeviceInfoBean device) {
        mOutputList.set(mPosition, device);
        setOutputList(mOutputList);
    }

    @Override
    public void whetherToSave(boolean hasModify) {
        if (hasModify){
            BaseDialog mDialog = new BaseDialog(mContext, new OnCallBackToRefresh() {
                @Override
                public void onConfirm() {
                    onSendAutomation();
                }

                @Override
                public void onCancel() {
                    mView.finishActivity();
                }
            });
            mDialog.setMsg(mContext.getString(R.string.scene_has_modify));
            mDialog.show();
        }else {
            mView.finishActivity();
        }
    }

    private String getDefaultStatus(String recommendId){
        switch (recommendId){
            case "19":
                return "20";
            case "28":
                return "60";
            case "2A":
            case "2C":
                return "40";
        }
        return "20";
    }
}
